<template>
	<view class="root">
		
		<mescroll-uni :top="0" bottom="62"  @down="downCallback" :up="upOption" @init="mescrollInit">
			<view class="message-list" >
				<view v-for="(msg, index) in messages.list" :key="index" :class="['box-bubble', msg.flow]" :id="`msg-${index}`"
					style="padding: 0 24rpx;">

					<image style="border-radius: 50%; background-color: #fff; width: 80rpx; height: 80rpx;" :src="msg.avatar"
						:alt="msg.nick" />

					<view v-if="msg.type === 'TIMTextElem'" :class="['bubble', msg.flow]">
						<rich-text style="word-break: break-all; padding: 10px;" :nodes="msg.payload.text" />
					</view>

					<view v-if="msg.type === 'TIMImageElem'" :class="['bubble', msg.flow]">
						<image @click="previewImage([msg.payload.imageInfoArray[0].imageUrl])" style="width: 200rpx;" mode="widthFix"
							:src="msg.payload.imageInfoArray[0].imageUrl" />
					</view>

					<view v-if="msg.type === 'TIMVideoFileElem'" :class="['bubble', msg.flow]">
						<view @click="playVideo(msg)" style="position: relative; width: 200rpx; font-size: 0;">
							<u-icon style="position: absolute; z-index: 9; top: 50%; left: 50%; transform: translate(-50%, -50%)"
								name="play-circle" color="#fff" size="60" />
							<image style="width: 100%;" mode="widthFix" :src="msg.payload.snapshotUrl" />
						</view>
					</view>
					
					<view v-if="msg.type === 'TIMSoundElem'" :class="['bubble', msg.flow]">
						<view @click="handlePlayAudio(msg.payload.url)">
							<u-icon name="wifi" class='audioMessage' :class="msg.flow === 'in'?'in':'out'"></u-icon>
						</view>
					</view>
				

					<view v-if="msg.type === 'TIMCustomElem'" @click="viewDetail(msg)" :class="['bubble', msg.flow]">
						<view class="chufang-head">
							<image style="width: 136rpx; height: 56rpx;" src="/static/img/kaichufang.png" alt="" />
							<view class="show-chufang">查看处方</view>
						</view>
						<text class="chufang-title">{{ msg.payload.data }}</text>
					</view>

				</view>
				<navigator :url="`/pages/mine/myConsultation/editor/prescribeEditor/index?user_id=${userID}`"
					class="prescription">
					开具处方
				</navigator>
			</view>
		</mescroll-uni>
		<view class="footText">
			<view class="textBox" v-show="!showAudio">
					<u-icon name="wifi" class='audioIcon' @click="handleShowAudio"></u-icon>
					<input v-model="messages.currentMsg" class="foot-input" confirm-type="send" >
					<view @click="selectOptions" class="radio">
						<u-icon name="plus" color="#000" size="28" />
					</view>
					<view class="sendBtn" @click="send">发送</view>
			</view>
			<view class="audioBox" v-show="showAudio" >
				<u-icon name="chat" class='chatIcon'  @click="handleShowAudio"></></u-icon>
				<view class="audioBtn"  @longpress="handleRudioMsg"  @touchend='handleTouchEnd'>
					<text>按住说话</text>
					
				</view>
				<view @click="selectOptions" class="radio">
					<u-icon name="plus" color="#000" size="28" />
				</view>
			</view>
			
		</view>

		<u-popup v-model="richText.show" mode="center" border-radius="14">
			<view style="padding: 30rpx;">
				<view style="font-weight: 700;width: 600rpx;">{{ richText.title }}</view>
				<view style="height: 30rpx;"></view>
				<scroll-view scroll-y="true" style="max-height: 70vh;width: 600rpx;">
					<rich-text :nodes="richText.content" />
				</scroll-view>
			</view>
		</u-popup>
		<u-popup v-model="video.show" mode="center" border-radius="20" :custom-style="{ fontSize: 0 }">
			<video style="width: 90vw; height: 60vh;" controls :src="video.src" />
		</u-popup>
		<!-- 讲语音时的mask -->
	<!-- 	<u-popup v-model="isSpeak" mode="center" border-radius="14">
			<img src="@/static/img/audioBtn.gif" class='audioClass' alt="">
		</u-popup> -->
	</view>
</template>

<script>
import api from "@/config/api.js";
import storage from "@/utils/storage";
import { TYPES, EVENT } from "@/js_sdk/tim/tim-js";
import mescrollUni from "@/components/mescroll-uni/mescroll-uni.vue"
export default {
	components:{
		mescrollUni
	},
	data() {
		return {
			isSpeak:false,
			showAudio: false,
			userID: "",
			prescribingData: {},
			patientData: {},
			messages: {
				currentMsg: "",
				list: [],
				nextReqMessageID: ""
			},
			richText: {
				title: "",
				show: false,
				nodes: ""
			},
			video: {
				show: false,
				src: "",
			},
			
			mescroll:null,
			downOption: {
				use: true,
				auto: false
			},
			upOption: {
				use: false, // 是否启用上拉加载; 默认true
				auto: false,
				page: {
					num: 0,
					size: 5
				},
				toTop:{
					src:''
				},
				noMoreSize: 1, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
				empty: {
					use : true,
					icon : '../../static/nodata.png',
					tip : "暂无数据",
					fixed: true,
					top: "200rpx",
					zIndex: 9
				},
				textNoMore:'无更多数据...',
				recorderManager: null,
				innerAudioContext:null
			},
		};
	},
	onUnload() {
		// this.$tim.logout();
	},
	
	onShow() {
		if(this.mescroll){
			this.messages.nextReqMessageID = '';
			this.mescroll.triggerDownScroll()
		}
	},
	onLoad({ user_id }) {
		
		this.userID = user_id;
		// 选择的处方
		this.prescribingData = uni.getStorageSync("e-prescribingDetail");
		// 当前病人
		this.patientData = uni.getStorageSync("patientInfo");
		
		this.$tim.on(EVENT.MESSAGE_RECEIVED, this.onMessageReceived, this);
		this.innerAudioContext = uni.createInnerAudioContext();
	},
	methods: {
		
		// 收到的消息
		onMessageReceived(value) {
			this.messages.list = [...this.messages.list,...value.data];
			this.mescroll.scrollTo(9999999, 0)
		},
		
		mescrollInit:function(mescroll) {
			this.mescroll = mescroll;  
		},
		// 点击语音消息播放语音
		handlePlayAudio(item) {
			if(!this.innerAudioContext.paused) {
				this.innerAudioContext.stop()
			}
			this.innerAudioContext.src = item;
			this.innerAudioContext.play();
		},
		// 切换到语音按钮
		handleShowAudio(){
			this.showAudio=!this.showAudio
		},
		// 长按触摸结束
		handleTouchEnd() {
				console.log('长按触摸结束')
			this.isSpeak = false
			uni.hideLoading()
				// 录音结束
			this.recorderManager.stop();
		},
		// 长按录音
		handleRudioMsg(){
			const that = this
			this.isSpeak = true
			this.recorderManager = uni.getRecorderManager();
			console.log('longpress')
			// 开始录音
			uni.showLoading()
			this.recorderManager.start();
			
			// 录音结束时 接收语音文件
			this.recorderManager.onStop(function (res) {
				console.log('recorder stop' + JSON.stringify(res),res);
				// self.voicePath = res.tempFilePath;
				that.createAudioMessage(res)
			});
			
			
			
		},
		// 创建音频消息
		createAudioMessage(res){
			var _this = this;
			let message = this.$tim.createAudioMessage({
				to: this.userID,
				conversationType: TYPES.CONV_C2C,
				payload: {
					file: res
				},
			});
			this.$tim.sendMessage(message).then(({ data }) => {
				this.messages.list.push(data.message);
				setTimeout(function() {
					_this.mescroll.scrollTo(9999999, 0)
				}, 200);
			}).catch((imError) => {
				console.warn('sendMessage error:', imError);
			});
		},
		downCallback:function(mescroll) {
			var _this = this;
			this.$tim.getMessageList({
				conversationID: `C2C${this.userID}`,
				nextReqMessageID: this.messages.nextReqMessageID,
				count: 15
			}).then(res => {
				if(res.data.isCompleted){
					_this.mescroll.lockDownScroll(true);
				}
				if(!_this.messages.nextReqMessageID ){
					_this.messages.list = [];
					setTimeout(function() {
						_this.mescroll.scrollTo(9999999, 0)
					}, 200);
				}
				_this.messages.nextReqMessageID = res.data.nextReqMessageID;
				_this.messages.list  = [...res.data.messageList, ..._this.messages.list];
				_this.mescroll.endSuccess();
				console.log(_this.messages.list,'_this.messages.list')
			});
		},
		viewDetail({ payload }) {
			const { data: title, description, extension } = payload,
				content = `${description}${extension && extension.split(",")}`;
			this.richText = { title, content, show: true }
		},
		previewImage(urls) {
			uni.previewImage({ urls });
		},
		playVideo({ payload }) {
			this.video.show = true;
			this.video.src = payload.remoteVideoUrl;
		},
		getMessageList({ isInit = false }) {
			if (!isInit && !this.messages.nextReqMessageID) return;
			if (isInit) this.messages.nextReqMessageID = null;
			this.$tim.getMessageList({
				conversationID: `C2C${this.userID}`,
				nextReqMessageID: this.messages.nextReqMessageID
			}).then(({ data }) => {
				
				this.messages.list = [...data.messageList, ...this.messages.list];
				this.messages.nextReqMessageID = data.nextReqMessageID;
				this.$nextTick(() => {
					this.$refs.msgBox && (this.$refs.msgList.scrollTop = this.$refs.msgBox.offsetHeight)
				});
			}).catch(err => console.log(err));
		},
		selectOptions() {
			var _this = this;
			let message = null;
			uni.showActionSheet({
				itemList: ["图片", "视频"],
				success: async ({
					tapIndex
				}) => {
					switch (tapIndex) {
						case 0: {
							const [, res] = await uni.chooseImage({
								count: 1
							});
							message = this.$tim.createImageMessage({
								to: this.userID,
								conversationType: TYPES.CONV_C2C,
								payload: {file: res},
								onProgress(event) {
									console.log('file uploading:', event)
								}
							});
						}
							break;
						case 1: {
							const [, res] = await uni.chooseVideo({
								maxDuration: 60
							});
							message = this.$tim.createVideoMessage({
								to: this.userID,
								conversationType: TYPES.CONV_C2C,
								payload: {
									file: res
								},
								onProgress(event) {
									console.log('file uploading:', event)
								}
							});
						}
							break;
						case 2:
							// iOS端无法选择系统文件
							break;
						default:
							break;
					}

					this.$tim.sendMessage(message).then(({data}) => {
						this.messages.list.push(data.message);
						setTimeout(function() {
							_this.mescroll.scrollTo(9999999, 0)
						}, 200);
					}).catch(imError => {
						// 发送失败
						console.warn('sendMessage error:', imError);
					});
				}
			});
		},
		send() {
			var _this = this;
			let message = this.$tim.createTextMessage({
				to: this.userID,
				conversationType: TYPES.CONV_C2C,
				payload: {
					text: this.messages.currentMsg
				},
			});
			this.$tim.sendMessage(message).then(({ data }) => {
				this.messages.list.push(data.message);
				setTimeout(function() {
					_this.mescroll.scrollTo(9999999, 0)
				}, 200);
			}).catch((imError) => {
				console.warn('sendMessage error:', imError);
			});

			this.messages.currentMsg = "";
		}
	},
}
</script>

<style lang="scss" scoped>
::v-deep.u-border-bottom {
	background-color: transparent !important;
}
.audioClass {
	height: 400rpx;
	width: 600rpx;
	object-fit: scale-down;
	
}
.chatIcon {
	border: 1px solid;
	border-radius: 50%;
	padding: 8rpx;
	margin-right: 10rpx;
}
.audioIcon {
	transform: rotateZ(90deg);
	border: 1px solid;
	border-radius: 50%;
	padding: 8rpx;
	margin-right: 10rpx;
}
.audioMessage {
	transform: rotateZ(-90deg);
	padding: 10rpx 20rpx;
}
.audioMessage.in {
	
		transform: rotateZ(90deg);
}
.audioMessage.out {
		transform: rotateZ(-90deg);
}

.root {
	height: 100%;
	display: flex;
	justify-content: flex-start;
	flex-direction: column;
}

.message-list {
	display: flex;
	flex: 1;
	flex-direction: column;
	box-sizing: border-box;
	overflow: hidden;
	padding: 30rpx;

	.box-bubble {
		display: flex;
		align-items: flex-start;
		margin-bottom: 24px;

		&.in {
			justify-content: left;
		}

		&.out {
			justify-content: right;
			flex-direction: row-reverse;
		}

		.bubble {
			display: flex;
			flex-direction: column;
			position: relative;
			overflow: hidden;
			max-width: 100%;
			margin-left: 52px;
			margin-right: 12px;
			font-size: 13px;
			color: #333;
			background-color: #fff;

			&.in {
				margin-right: 52px;
				margin-left: 12px;
				border-radius: 0 6px 6px 6px;
			}

			&.out {
				margin-left: 52px;
				margin-right: 12px;
				border-radius: 6px 0 6px 6px;
			}

			.chufang-head {
				padding: 6px 10px;
				display: flex;
				align-items: center;
				justify-content: space-between;
				background-color: #2375ff;

				.show-chufang {
					cursor: pointer;
					padding: 0 9px;
					line-height: 2;
					border: 1px solid #fff;
					color: #fff;
					border-radius: 9px;
				}
			}

			.chufang-title {
				width: 220px;
				padding: 10px;
				color: #176eff;
			}
		}
	}
}

.prescription {
	position: fixed;
	left: 30rpx;
	bottom: 200rpx;
	padding: 0 30rpx;
	width: 32;
	height: 80rpx;
	color: #4c79e4;
	font-size: 30rpx;
	font-weight: bold;
	line-height: 80rpx;
	background-color: #fff;
	border-radius: 40rpx;
	text-align: center;
}


.footText {
	// position: fixed;
	width: 100%;
	bottom: 20rpx;
	border-top: 1px solid #E3E3E3;
	
	padding: 30rpx;
	z-index: 9;
	background: rgb(245,245,245);
	.textBox {
		display: flex;
		align-items: center;
		justify-content: space-around;
	}
		
	.audioBox {
		display: flex;
		align-items: center;
		justify-content: space-around;
		.audioBtn {
			flex: 1;
			text-align: center;
			border: 1px solid #dedede;
			background-color: #fff;
			padding: 10rpx 0;
		}
		.audioBtn:active {
			// box-shadow: 1rpx 1rpx 1rpx #000;
			box-shadow: 0 2rpx 4rpx 0 rgba(0,0,0,0.2), 0 1rpx 5rpx 0 rgba(0,0,0,0.19);
		}
	}
	.foot-input {
		width: 68%;
		height: 60rpx;
		padding: 0 24rpx;
		background: #ffffff;
		border-radius: 35rpx;
	}

	.radio {
		width: 49rpx;
		height: 49rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-left: 24rpx;
		border: 4rpx solid #333333;
		border-radius: 50%;
		font-size: 40rpx;
		font-weight: bold;
	}
	.sendBtn{
		padding: 10rpx 0;
		width: 100rpx;
		margin-left: 20rpx;
		text-align: center;
		border-radius: 10rpx;
		border: 1rpx solid gray;
		font-size: 28rpx;
	}
}
</style>
